﻿using CoachingOrganizer.Logic.Common;
using CoachingOrganizer.Logic.Models.Tools.MoodLevel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CoachingOrganizer.Logic.Logic.Tools.MoodLevel
{
    internal class MoodValueCacheLogic
    {
        private readonly MoodValueCacheModel _model;
        private readonly LogicExtender _logicExtender;
        private readonly MoodDayCacheLogic _upperLogic;
        private readonly MoodLevelLogic _overUpperLogic;

        public MoodValueCacheModel Model
        {
            get { return _model; }
        }

        public MoodValueCacheLogic(LogicExtender logicExtender, MoodDayCacheLogic upperLogic, MoodLevelLogic overUpperLogic, DateTime time)
            : this(new MoodValueCacheModel(time), logicExtender, upperLogic, overUpperLogic)
        {

        }

        public MoodValueCacheLogic(MoodValueCacheModel model, LogicExtender logicExtender, MoodDayCacheLogic upperLogic, MoodLevelLogic overUpperLogic)
        {
            _model = model;
            _logicExtender = logicExtender;
            _upperLogic = upperLogic;
            _overUpperLogic = overUpperLogic;
            model.UpdateDataModelDelegate = UpdateDataModel;
        }

        private void UpdateDataModel(double? rawValue)
        {
            if (!rawValue.HasValue)
                return;
            double value = rawValue.Value;
            MoodValueModel valueModel = _overUpperLogic.Model.Values.FirstOrDefault(v => v.Time == _model.Time);
            if (valueModel == null)
                _overUpperLogic.AddValue(_model.Time, value);
            else
                valueModel.Value = value;
        }

        private void UpdateFromDataModel()
        {
            MoodValueModel machtingValueModel = _overUpperLogic.EnumerateDayValues(_upperLogic.Model.Date).FirstOrDefault(v => v.Time == _model.Time);
            if (machtingValueModel != null)
                _model.Value = machtingValueModel.Value;
        }
    }
}
